package top.scsoul.pas.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import top.scsoul.pas.entity.Clazz;
import top.scsoul.pas.entity.Student;
import top.scsoul.pas.repository.AchievementRepository;
import top.scsoul.pas.repository.ClazzRepository;
import top.scsoul.pas.repository.StudentReposotory;
import top.scsoul.pas.service.StudentService;
import org.springframework.stereotype.Service;
import top.scsoul.pas.utils.StringUtil;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * (Student)表服务实现类
 *
 * @author makejava
 * @since 2021-06-16 14:45:55
 */
@Transactional(rollbackOn = Exception.class)
@Slf4j
@Service
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentReposotory studentReposotory;
    @Autowired
    ClazzRepository classRepository;

    @Autowired
    AchievementRepository achievementRepository;

    @Override
    public Student queryById(Long id) {
        return studentReposotory.getById(id);
    }

    @Override
    public Page<Student> listStudent(int currentPage, int pageSize) {
        PageRequest pageRequest = PageRequest.of(currentPage - 1, pageSize);
        return studentReposotory.findAll(pageRequest);
    }

    @Override
    public Student insert(Student student) {
        //身份证验证
        long count = studentReposotory.getCountByCard(student.getCard());
        if (count > 0) {
            throw new RuntimeException("身份证号码已经存在");
        }
        return studentReposotory.save(student);
    }

    @Override
    public Student update(Student student) {
        Student studentById = studentReposotory.getById(student.getId());
        String card = studentById.getCard();
        if (!card.equals(student.getCard())) {
            //身份证验证
            long count = studentReposotory.getCountByCard(student.getCard());
            if (count > 0) {
                throw new RuntimeException("身份证号码已经存在");
            }
        }
        return studentReposotory.save(student);
    }

    @Override
    public void deleteById(Long id) {
        //先删除外键约束
        achievementRepository.delByStudentId(id);
        studentReposotory.deleteById(id);
    }

    @Override
    public void deleteByClazzId(Long id) {
        studentReposotory.deleteByClazzId(id);
    }

    @Override
    public List<Student> getStudentsByClazzId(Long clazzId) {
        return studentReposotory.getStudentsByClazzId(clazzId);
    }
}